//
//  LottieLoading.m
//  Shengzhuli
//
//  Created by FXGuo on 2018/1/23.
//  Copyright © 2018年 kamangkeji. All rights reserved.
//

#import "LottieLoading.h"
#import <Lottie/Lottie.h>

@interface LottieLoading()

@property (nonatomic,assign) BOOL isReadyRemove;
@property (nonatomic,strong) LOTAnimationView *animationView;

@end

@implementation LottieLoading

+ (void)showLoadingInView:(UIView *)view
{
    if (view == nil) view = [[UIApplication sharedApplication].windows lastObject];
    LottieLoading *hud = [[LottieLoading alloc]initWithFrame:view.bounds];
    [view addSubview:hud];
    
    float width = 100;
    LOTAnimationView *animationView = [LOTAnimationView animationNamed:@"loading_animation"];
    animationView.frame = CGRectMake((view.width-width)/2.0, (view.height-width)/2.0, width, width);
    animationView.contentMode = UIViewContentModeScaleAspectFit;
    animationView.loopAnimation = YES;
    [view addSubview:animationView];
    [animationView play];
    hud.animationView = animationView;
}
+ (void)hideLoadingInView:(UIView *)view
{
    if (view == nil) view = [[UIApplication sharedApplication].windows lastObject];
    LottieLoading * hud = [self getIndicatorHudWithView:view];
    if (hud!=nil) {
        hud.isReadyRemove = YES;
        [UIView animateWithDuration:0.5 animations:^{
            hud.animationView.alpha = 0.0;
        } completion:^(BOOL finished) {
            [hud removeFromSuperview];
//            [hud.animationView pause];
        }];
    }  
}
//获取LottieLoading方法
+ (LottieLoading *)getIndicatorHudWithView:(UIView *)view
{
    NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
    for (UIView *subview in subviewsEnum) {
        if ([subview isKindOfClass:self]) {
            LottieLoading *hud = (LottieLoading *)subview;
            if (hud.isReadyRemove) {
                continue;
            }
            return hud;
        }
    }
    return nil;
}

@end
